import jwt
import datetime
from rest_framework.views import APIView
from rest_framework.response import Response
from ..serializers.account import AuthSerializer
from utils import return_code
from .. import models
from django.conf import settings


class AuthView(APIView):
    authentication_classes = []
    permission_classes = []

    def post(self, request, *args, **kwargs):
        serializer = AuthSerializer(data=request.data)
        if not serializer.is_valid():
            return Response({"code": return_code.FIELD_ERROR, "detail": serializer.errors})
        username = serializer.validated_data.get('username')
        password = serializer.validated_data.get('password')
        user_object = models.UserInfo.objects.filter(username=username, password=password).first()
        if not user_object:
            return Response({"code": return_code.VALIDATE_ERROR, "detail": "用户名或密码错误"})
            # 登录成功，生成jwt token
        headers = {
            'typ': 'jwt',
            'alg': 'HS256'
        }
        # 构造payload
        payload = {
            'user_id': user_object.id,
            'username': user_object.username,
            "exp": datetime.datetime.utcnow() + datetime.timedelta(seconds=5)
        }
        jwt_token = jwt.encode(payload=payload, key=settings.SECRET_KEY, algorithm="HS256", headers=headers)

        return Response({"code": return_code.SUCCESS, "data": {"token": jwt_token, "username": user_object.username}})


class TestView(APIView):
    def get(self, request, *args, **kwargs):
        # print(request.user.username)
        print(request.auth)
        print(request.user.user_id)
        print(request.user.username)
        print(request.user.exp)
        return Response('test')
